package com.rtx.wms.customer.grp.handler.qcapply;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.customer.common.upload.UploadService;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.qc.bean.RtxQcapply;
import com.rtx.wms.std.qc.service.RtxQcapplyService;

import cn.hutool.core.util.StrUtil;

/**
 * 复检申请
 * @author Administrator
 *
 */
@Component
public class GrpQcApplyHandle {
	
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    RtxQcapplyService rtxQcapplyService;
    
    @Autowired
    ApplicationContext applicationContext;
	
    @DataSourceAnnotation
    public void handlerUpload(String whseid,ApiMappingInfoBo bo){
        //获取入库单回传数据
        List<RtxQcapply> list = selectRtxQcapply(whseid);
        
        for(RtxQcapply o : list){
            //回传
        	UploadService service = (UploadService)applicationContext.getBean(bo.getApimappingcode());
        	service.uploadHandle(o);
            //更新状态
            updateStatus(whseid,o);
        }
    }

    /**
     * 更新
     * @param whseid
     * @param o
     */
    private void updateStatus(String whseid, RtxQcapply o) {
        try {
            LambdaUpdateWrapper<RtxQcapply> wrapper = Wrappers.lambdaUpdate();
            wrapper.eq(RtxQcapply::getSerialkey,o.getSerialkey())
                    .set(RtxQcapply::getRtxeditflag,o.getRtxeditflag())
                    .set(RtxQcapply::getRtxmsgErp,StrUtil.sub(o.getRtxmsgErp(),0,499))
                    .set(RtxQcapply::getRtxqueue,o.getRtxqueue() + 1);
            rtxQcapplyService.updStatus(whseid,wrapper);
            
        } catch (Exception e) {
            logger.error("复检申请：{}更新回传状态异常",o.getRtxchecklist(),e);
        }
    }

    /**
     * 获取复检申请数据
     * @param whseid
     * @return
     */
    public List<RtxQcapply> selectRtxQcapply(String whseid){
        LambdaQueryWrapper<RtxQcapply> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper .eq(RtxQcapply::getType, "YJ")
        			.eq(RtxQcapply::getRtxeditflag, WmsConstant.DEFAULT_FLAG)
                    .lt(RtxQcapply::getRtxqueue,10);
        List<RtxQcapply> list = rtxQcapplyService.queryRtxQcapply(whseid,queryWrapper);
        return list;
    }
}
